package thesis.filesharing.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import thesis.filesharing.bo.LecturerBO;
import thesis.filesharing.bo.SubjectBO;
import thesis.filesharing.resources.Constants;
import thesis.filesharing.web.viewmodel.UpdateClassViewModel;

public class UpdateClassValidator implements Validator {
	
	@Autowired
	private SubjectBO subjectBO;
	
	@Autowired
	private LecturerBO lecturerBO;
	
	@Override
	public boolean supports(Class<?> clazz) {
		return UpdateClassViewModel.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "className", "className.needed");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "subjectId", "subjectId.required");
		
		UpdateClassViewModel model = (UpdateClassViewModel) target;
		
		if (model.getSubjectId() != null && model.getSubjectId().length() > 0) {
			Pattern subjectIdPattern = Pattern.compile(Constants.SUBJECT_ID_PATTERN, Pattern.CASE_INSENSITIVE);
			Matcher subjectIdMatcher = subjectIdPattern.matcher(model.getSubjectId());
			if (!subjectIdMatcher.matches()) {
				errors.rejectValue("subjectId", "subjectId.incorrectFormat");
			}
		}
		
		if (model.getLecturerId() != null && model.getLecturerId().length() > 0) {
			Pattern lecturerIdPattern = Pattern.compile(Constants.LECTURER_ID_PATTERN);
			Matcher lecturerIdMatcher = lecturerIdPattern.matcher(model.getLecturerId());
			if (!lecturerIdMatcher.matches()) {
				errors.rejectValue("lecturerId", "lecturerId.incorrectFormat");
			}
		}
		
		if (!errors.hasErrors()) {
			if (model.getSubjectId() != null && model.getSubjectId().length() > 0
					&& subjectBO.findSubjectById(model.getSubjectId()) == null) {
				errors.reject("subjectId.notExisted");
			}
			
			if (model.getLecturerId() != null && model.getLecturerId().length() > 0
					&& lecturerBO.findLecturerById(model.getLecturerId()) == null) {
				errors.reject("lecturerId.notExisted");
			}
		}
	}
}
